package org.sky.component.fileupload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.sky.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class FileHelper {
	private static Logger log=LoggerFactory.getLogger(FileHelper.class);

	/**上传文件
	 *@param uploadfile 上传的文件
	 *@return String
	 * @throws IOException 
	 *
	 */
	public static String fileUpload(File uploadFile,String fileName,String rootPath,HttpServletRequest request) throws IOException {
			String realpath = rootPath;
			String path = request.getSession().getServletContext().getRealPath(realpath);
			String fileshortName="_upload";
			String suffix=fileName.substring(fileName.indexOf("."),fileName.length());
			String fileNameandTime=fileshortName+"_"+DateUtil.getCurrentTime("yyyyMMddHHmmss")+suffix;
			log.info(fileshortName+"-"+suffix+"-"+fileNameandTime);
			File savefile = new File(new File(path),fileNameandTime);
			FileUtils.copyFile(uploadFile , savefile); 
		return fileNameandTime;
	};
	
	/**下载文件
	 *@param filePath 被下载的文件路径
	 *@return 文件
	 * @throws FileNotFoundException 
	 */
	/*public static FileInputStream fileDownload(String pathFileName,String rootDownPath) throws FileNotFoundException{
		//去相对路径的文件；
		//ServletActionContext.getServletContext().getResourceAsStream("/uploadfile/ws.txt");
		String path=ServletActionContext.getServletContext().getRealPath(rootDownPath);
		log.info("path----->"+path+pathFileName);
		//去绝对路径的文件
		return new FileInputStream(path+"\\"+pathFileName);
	};*/
	/**
	 * 上传
	 * @param file
	 * @param filename
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static String upload(File file,InputStream fips,String filename,String path,HttpServletRequest request) throws Exception{
		File dir =new File(request.getSession().getServletContext().getRealPath(path));    
		//如果文件夹不存在则创建    
		if  (!dir .exists())      
		{       
		    System.out.println("不存在");  
		    dir.mkdir();    
		}
		//文件名字	
		Long systime = System.currentTimeMillis();
		String newfilename= systime.toString()+"_"+filename;
		//输出流
		FileOutputStream fos = null;
		//输入流
		InputStream fis = null;
		if(file != null){
			fis = new FileInputStream(file);
		}else if(fips != null){
			fis=fips;
		}
		fos = new FileOutputStream(request.getSession().getServletContext().getRealPath(path) + "/"+ newfilename);
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = fis.read(buffer)) > 0) {
			fos.write(buffer, 0, len);
		}
		fos.flush();
		fis.close();
		fos.close();
		return path+"/"+newfilename;
	
	}
	
	/**删除目录
	 * @param dir
	 * @return
	 */
	public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
	
	/**删除目录
	 * @param dir
	 * @return
	 */
	public static boolean deleteDirForPath(String dirpath) {
		File dir=new File(dirpath);
		return deleteDir(dir);
	}
	/**断点续传
	 * @return
	 * @throws IOException 
	 */
	public static void uploadFBreak(String filePath,InputStream ips,HttpServletRequest request) throws IOException{
		//获取已近存在的文件
		File oldFile =new File(request.getSession().getServletContext().getRealPath(filePath));
		
		RandomAccessFile randomAccessFile = new RandomAccessFile(oldFile, "rw");
		randomAccessFile.seek(oldFile.length());
		
		try{
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = ips.read(buffer)) > 0) {
				randomAccessFile.write(buffer, 0, len);
			}
		}finally{
			ips.close();
			randomAccessFile.close();
		}

	}
	
	/**获得文件大小
	 * @param filePath
	 * @return
	 */
	public static Long getFileSize(String filePath,HttpServletRequest request){
		//获取已近存在的文件
		File file =new File(request.getSession().getServletContext().getRealPath(filePath));
		Long length=0L;
		try{
			length=file.length();
		}catch(Exception e){
			
		}finally{
		
		}
		return length;
	}
}
